import { Route } from '@/types';
import ofetch from '@/utils/ofetch';
import { getBuildId, getData } from './utils';
import { parseDate } from '@/utils/parse-date';

export const route: Route = {
    path: '/:type',
    categories: ['new-media', 'popular'],
    example: '/aeon/essays',
    parameters: {
        type: {
            description: 'Type',
            options: [
                { value: 'essays', label: 'Essays' },
                { value: 'videos', label: 'Videos' },
                { value: 'audio', label: 'Audio' },
            ],
        },
    },
    features: {
        requireConfig: false,
        requirePuppeteer: false,
        antiCrawler: false,
        supportBT: false,
        supportPodcast: false,
        supportScihub: false,
    },
    radar: [
        {
            source: ['aeon.co/:type'],
        },
    ],
    name: 'Types',
    maintainers: ['emdoe'],
    handler,
    description: `Supported types: Essays, Videos, and Audio.

  Compared to the official one, the RSS feed generated by RSSHub not only has more fine-grained options, but also eliminates pull quotes, which can't be easily distinguished from other paragraphs by any RSS reader, but only disrupt the reading flow. This feed also provides users with a bio of the author at the top.`,
};

async function handler(ctx) {
    const type = ctx.req.param('type');
    const capitalizedType = type.charAt(0).toUpperCase() + type.slice(1);

    const buildId = await getBuildId();
    const url = `https://aeon.co/${type}`;
    const response = await ofetch(`https://aeon.co/_next/data/${buildId}/${type}.json`);

    const list = response.pageProps.articles.map((node) => ({
        title: node.title,
        description: node.standfirstLong,
        author: node.authors.map((author) => author.displayName).join(', '),
        link: `https://aeon.co/${node.type}s/${node.slug}`,
        pubDate: parseDate(node.createdAt),
        category: [node.section.title, ...node.topics.map((topic) => topic.title)],
        image: node.image.url,
        type: node.type,
        slug: node.slug,
    }));

    const items = await getData(list);

    return {
        title: `AEON | ${capitalizedType}`,
        link: url,
        item: items,
    };
}
